package com.atguigu.gmall.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.app.BaseAppV1;
import com.atguigu.gmall.common.Constant;
import com.atguigu.gmall.util.AtguiguCommonUtil;
import com.atguigu.gmall.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/28 9:14
 */
/*
对日志数据进行分流, 写入到dwd层(kafka)

1. 对新老用户进行确认

2. 对ods_log流进行分流(使用侧输出流)
    不同的数据放入不同的流
        启动日志
        曝光日志
        页面日志
        
3. 把数据写入到Kafka中

 */
public class DwdLogApp extends BaseAppV1 {
    final String START_STREAM = "start";
    final String PAGE_STREAM = "page";
    final String DISPLAY_STREAM = "display";
    
    public static void main(String[] args) {
        new DwdLogApp().init(
            2001,
            1,
            "DwdLogApp",
            "DwdLogApp",
            Constant.TOPIC_ODS_LOG
        );
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env,
                       DataStreamSource<String> sourceStream) {
        // 实现业务
        
        //1. 对新老用户进行确认
        SingleOutputStreamOperator<JSONObject> validatedStream = distinguishNewOrOld(sourceStream);
        // 2. 不同的日志进入不同的流
        Map<String, DataStream<JSONObject>> threeStreams = splitSteam(validatedStream);
        // 3. 把数据写入到kafka中
        sendToKafka(threeStreams);
        
    }
    
    private void sendToKafka(Map<String, DataStream<JSONObject>> threeStreams) {
        threeStreams
            .get(START_STREAM)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_START));
        
        threeStreams
            .get(PAGE_STREAM)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_PAGE));
        
        threeStreams
            .get(DISPLAY_STREAM)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_DISPLAY));
        
    }
    
    private Map<String, DataStream<JSONObject>> splitSteam(SingleOutputStreamOperator<JSONObject> stream) {
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {};
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display") {};
        // 把日志分成了3类:
        // 1. 启动日志  主流
        // 2. 页面日志   侧输出流
        // 3. 曝光日志   侧输出流
        SingleOutputStreamOperator<JSONObject> startStream = stream.process(new ProcessFunction<JSONObject, JSONObject>() {
            @Override
            public void processElement(JSONObject value,
                                       Context ctx,
                                       Collector<JSONObject> out) throws Exception {
                JSONObject start = value.getJSONObject("start");
                if (start != null) { // 启动日志放入主流
                    out.collect(value);
                } else {
                    
                    JSONObject page = value.getJSONObject("page");
                    if (page != null) {
                        ctx.output(pageTag, value);
                    }
                    
                    JSONArray displays = value.getJSONArray("displays");
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            // 在display中补充一些数据
                            // 1. 补充时间戳
                            display.put("ts", value.getLong("ts"));
                            // 2. 补充一个page_id
                            display.put("page_id", value.getJSONObject("page").getString("page_id"));
                            // 3. 补充common中所有的字段
                            display.putAll(value.getJSONObject("common"));
                            ctx.output(displayTag, display);
                        }
                    }
                    
                }
            }
        });
        
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        
        HashMap<String, DataStream<JSONObject>> result = new HashMap<>();
        result.put(START_STREAM, startStream);
        result.put(PAGE_STREAM, pageStream);
        result.put(DISPLAY_STREAM, displayStream);
        return result;
        
    }
    
    private SingleOutputStreamOperator<JSONObject> distinguishNewOrOld(DataStreamSource<String> sourceStream) {
        // 如何实现识别新老客户?
        // 需要利用状态
        // 考虑数据的乱序: 使用事件时间, 加窗口
        return sourceStream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<Long> firstWidowState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstWidowState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("firstWidowState", Long.class));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    // 如果识别出来某个mid的第一个窗口
                    if (firstWidowState.value() == null) {
                        // 把时间戳最小的那个条记录的is_new设置为1, 其他都为0
                        List<JSONObject> list = AtguiguCommonUtil.toList(elements);
                        //                        list.sort((o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                        list.sort(Comparator.comparing(o -> o.getLong("ts")));
                        
                        for (int i = 0; i < list.size(); i++) {
                            JSONObject common = list.get(i).getJSONObject("common");
                            if (i == 0) {
                                common.put("is_new", "1");
                                // 更新状态
                                firstWidowState.update(list.get(i).getLong("ts"));
                            } else {
                                common.put("is_new", "0");
                            }
                            
                            out.collect(list.get(i));
                        }
                        
                    } else {
                        // 所有的用户都是旧用户, 所有的is_new全部设置为0
                        for (JSONObject element : elements) {
                            element.getJSONObject("common").put("is_new", "0");
                            out.collect(element);
                            
                        }
                    }
                    
                }
            });
        
    }
}
